import type { SelectProps } from 'antd';
import { Select, Spin } from 'antd';
import React, { useEffect, useState } from 'react';
type Item = { label: string; value: string; disabled?: boolean };
export const SelectSearchIpt: React.FC<{
  searchFun: Function; //搜索方法
  placeholder?: string;
  style?: React.CSSProperties;
  defaultValue?: string;
  memberName?: string;
  onChange?: (value: string) => void;
  onChangeCall?(val: string): void;
}> = (props) => {
  const [data, setData] = useState<SelectProps['options']>([]);
  const [value, setValue] = useState<string>();
  const [fetching, setFetching] = useState<boolean>(false);

  let timeout: ReturnType<typeof setTimeout> | null;
  let currentValue: string;
  const fetch = (value: string, callback: Function) => {
    if (timeout) {
      clearTimeout(timeout);
      timeout = null;
    }
    currentValue = value;

    const fake = async () => {
      const listData: any[] = await props.searchFun(currentValue);
      setFetching(false);
      callback(listData);
    };

    timeout = setTimeout(fake, 300);
  };
  const handleSearch = (newValue: string) => {
    setFetching(true);
    fetch(newValue, setData);
  };

  const handleChange = (newValue: string) => {
    setValue(newValue);
    props.onChange?.(newValue);
  };
  //初始化
  useEffect(() => {
    fetch('', setData);
  }, []);
  return (
    <>
      <Select
        showSearch
        value={value}
        allowClear={true}
        defaultValue={props.defaultValue}
        placeholder={props.placeholder}
        style={props.style}
        defaultActiveFirstOption={false}
        showArrow={false}
        filterOption={false}
        onSearch={handleSearch}
        onChange={(v) => handleChange(v)}
        notFoundContent={fetching ? <Spin size="small" /> : null}
        options={(data || []).map((d) => ({
          value: d.value,
          label: d.text,
          disabled: d.disabled,
        }))}
      />
    </>
  );
};
